{% extends "base.html" %}

{% block title %}SimpleTrade - 基金配置管理{% endblock %}

{% block extra_css %}
    <style>
        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        th {
            background-color: #3498db;
            color: white;
            font-weight: 600;
        }
        tr:hover {
            background-color: #f8fafc;
        }
        tr:last-child td {
            border-bottom: none;
        }

        /* 动画效果 */
        .delete-row {
            animation: deleteFade 0.5s forwards;
        }
        .update-row {
            animation: highlight 1.5s;
        }
        .new-row {
            animation: highlight 1.5s;
        }
        @keyframes deleteFade {
            from { opacity: 1; }
            to { opacity: 0; transform: translateX(-20px); }
        }
        @keyframes highlight {
            0% { background-color: #e3f2fd; }
            100% { background-color: transparent; }
        }

        /* 弹窗样式（添加和编辑通用） */
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 400px;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            animation: modalFadeIn 0.3s;
        }
        @keyframes modalFadeIn {
            from {opacity: 0; transform: translateY(-20px);}
            to {opacity: 1; transform: translateY(0);}
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: black;
        }

        /* 按钮和表单样式 */
        .btn {
            display: inline-block;
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            transition: background-color 0.2s;
        }
        .btn:hover {
            background-color: #45a049;
        }
        .btn-edit {
            background-color: #008CBA;
            margin-right: 5px;
        }
        .btn-edit:hover {
            background-color: #007B9A;
        }
        .btn-delete {
            background-color: #f44336;
        }
        .btn-delete:hover {
            background-color: #d32f2f;
        }

        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #555;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            transition: border-color 0.2s;
        }
        .form-group input:focus {
            border-color: #3498db;
            outline: none;
        }
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        /* 提示信息和加载动画 */
        .message {
            padding: 10px;
            margin: 15px 0;
            border-radius: 4px;
            display: none;
            animation: fadeIn 0.3s;
        }
        @keyframes fadeIn {
            from {opacity: 0;}
            to {opacity: 1;}
        }
        .message-success {
            background-color: #d4edda;
            color: #155724;
            display: block;
        }
        .message-error {
            background-color: #f8d7da;
            color: #721c24;
            display: block;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            vertical-align: middle;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
{% endblock %}

{% block content %}
    <h2 class="section-title">基金配置管理</h2>

    <div id="operation-message" class="message"></div>

    <button class="btn" id="add-fund-btn">添加基金</button>

    <!-- 添加基金弹窗 -->
    <div id="add-fund-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加新基金</h3>
                <span class="close" data-modal="add-fund-modal">&times;</span>
            </div>

            <form id="add-fund-form">
                <input type="hidden" id="fund-id" name="fund_id">

                <div class="form-group">
                    <label for="fund-code">基金代码<span style="color: red; margin-left: 2px;">*</span></label>
                    <input type="text" id="fund-code" name="code" required placeholder="必填">
                </div>

                <div class="form-group">
                    <label for="fund-name">基金名称</label>
                    <input type="text" id="fund-name" name="name" placeholder="可选">
                </div>

                <div class="form-actions">
                    <button type="button" class="btn btn-delete cancel-modal" data-modal="add-fund-modal">取消</button>
                    <button type="submit" class="btn">
                        <span id="save-btn-text">保存</span>
                        <span id="save-loading" class="loading" style="display:none;"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑基金弹窗 -->
    <div id="edit-fund-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>编辑基金</h3>
                <span class="close" data-modal="edit-fund-modal">&times;</span>
            </div>

            <form id="edit-fund-form">
                <input type="hidden" id="edit-fund-id" name="fund_id">

                <div class="form-group">
                    <label for="edit-fund-code">基金代码</label>
                    <input type="text" id="edit-fund-code" name="code" required placeholder="例如：000001">
                </div>

                <div class="form-group">
                    <label for="edit-fund-name">基金名称</label>
                    <input type="text" id="edit-fund-name" name="name" required placeholder="例如：华夏成长混合">
                </div>

                <div class="form-actions">
                    <button type="button" class="btn btn-delete cancel-modal" data-modal="edit-fund-modal">取消</button>
                    <button type="submit" class="btn">
                        <span id="edit-save-text">保存修改</span>
                        <span id="edit-loading" class="loading" style="display:none;"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="fund-table-container">
        <table id="fund-table">
            <tr>
                <th>基金代码</th>
                <th>基金名称</th>
                <th>操作</th>
            </tr>
            {% for fund_id, fund in funds.items() %}
            <tr data-fund-id="{{ fund_id }}">
                <td class="fund-code">{{ fund.code }}</td>
                <td class="fund-name">{{ fund.name }}</td>
                <td>
                    <button class="btn btn-edit edit-fund-btn" data-fund-id="{{ fund_id }}">编辑</button>
                    <button class="btn btn-delete delete-btn" data-fund-id="{{ fund_id }}">删除</button>
                </td>
            </tr>
            {% endfor %}
        </table>
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        // 生成UUID
        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        // 显示提示信息
        function showMessage(text, type) {
            const msgEl = document.getElementById('operation-message');
            msgEl.textContent = text;
            msgEl.className = `message message-${type}`;
            setTimeout(() => {
                msgEl.className = 'message';
            }, 3000);
        }

        // 关闭弹窗通用函数
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // 初始化弹窗事件（关闭和取消按钮）
        document.querySelectorAll('.close, .cancel-modal').forEach(el => {
            el.addEventListener('click', () => {
                const modalId = el.getAttribute('data-modal');
                closeModal(modalId);
            });
        });

        // 点击弹窗外部关闭
        window.addEventListener('click', (event) => {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        });

        // ------------ 添加基金功能 ------------
        document.getElementById('add-fund-btn').addEventListener('click', () => {
            // 重置表单并显示弹窗
            document.getElementById('add-fund-form').reset();
            document.getElementById('fund-id').value = generateUUID();
            document.getElementById('add-fund-modal').style.display = 'block';
        });

        // 提交添加基金表单
        document.getElementById('add-fund-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const form = e.target;
            const fundId = form.querySelector('#fund-id').value;
            const code = form.querySelector('#fund-code').value.trim();
            const name = form.querySelector('#fund-name').value.trim();
            const saveBtn = form.querySelector('button[type="submit"]');
            const saveText = document.getElementById('save-btn-text');
            const saveLoading = document.getElementById('save-loading');

            // 前端验证
            if (code.length !== 6 || !/^\d{6}$/.test(code)) {
                showMessage('基金代码必须是6位数字', 'error');
                return;
            }

            // 显示加载状态
            saveBtn.disabled = true;
            saveText.style.display = 'none';
            saveLoading.style.display = 'inline-block';

            try {
                // 发送添加请求
                const response = await fetch('{{ url_for('fund_config.add_fund') }}', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({fund_id: fundId, code, name})
                });
                const result = await response.json();

                if (result.success) {
                    // 前端动态添加新行
                    addNewFundToTable(fundId, code, result.data.fund_name);
                    showMessage('基金添加成功', 'success');
                    closeModal('add-fund-modal');
                } else {
                    showMessage(`添加失败：${result.error}`, 'error');
                }
            } catch (error) {
                console.error('添加失败:', error);
                showMessage('网络错误，添加失败', 'error');
            } finally {
                // 恢复按钮状态
                saveBtn.disabled = false;
                saveText.style.display = 'inline';
                saveLoading.style.display = 'none';
            }
        });

        // 动态添加新基金到表格
        function addNewFundToTable(fundId, code, name) {
            const tableBody = document.querySelector('#fund-table tbody') || document.querySelector('#fund-table');
            const newRow = document.createElement('tr');
            newRow.className = 'new-row';
            newRow.setAttribute('data-fund-id', fundId);

            newRow.innerHTML = `
                <td class="fund-code">${code}</td>
                <td class="fund-name">${name}</td>
                <td>
                    <button class="btn btn-edit edit-fund-btn" data-fund-id="${fundId}">编辑</button>
                    <button class="btn btn-delete delete-btn" data-fund-id="${fundId}">删除</button>
                </td>
            `;

            tableBody.appendChild(newRow);
            // 绑定新行的编辑和删除事件
            bindEditEvent(newRow.querySelector('.edit-fund-btn'));
            bindDeleteEvent(newRow.querySelector('.delete-btn'));
        }

        // ------------ 编辑基金功能 ------------
        // 绑定编辑按钮事件
        function bindEditEvent(button) {
            button.addEventListener('click', async () => {
                const fundId = button.getAttribute('data-fund-id');

                try {
                    // 使用专门的获取基金信息接口
                    const response = await fetch(`/fund-config/${fundId}`);
                    const result = await response.json();

                    if (result.success) {
                        // 填充编辑表单
                        const form = document.getElementById('edit-fund-form');
                        form.querySelector('#edit-fund-id').value = result.fund.id;
                        form.querySelector('#edit-fund-code').value = result.fund.code;
                        form.querySelector('#edit-fund-name').value = result.fund.name;
                        document.getElementById('edit-fund-modal').style.display = 'block';
                    } else {
                        showMessage(result.error, 'error');
                    }
                } catch (error) {
                    console.error('获取基金信息失败:', error);
                    showMessage('获取基金信息失败', 'error');
                }
            });
        }

        // 提交编辑表单
        document.getElementById('edit-fund-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const form = e.target;
            const fundId = form.querySelector('#edit-fund-id').value;
            const newCode = form.querySelector('#edit-fund-code').value.trim();
            const newName = form.querySelector('#edit-fund-name').value.trim();
            const saveBtn = form.querySelector('button[type="submit"]');
            const saveText = document.getElementById('edit-save-text');
            const saveLoading = document.getElementById('edit-loading');

            // 前端验证
            if (newCode.length !== 6 || !/^\d{6}$/.test(newCode)) {
                showMessage('基金代码必须是6位数字', 'error');
                return;
            }

            // 显示加载状态
            saveBtn.disabled = true;
            saveText.style.display = 'none';
            saveLoading.style.display = 'inline-block';

            try {
                // 发送更新请求（注意：使用新的API路径）
                const response = await fetch(`{{ url_for('fund_config.edit_fund', fund_id='PLACEHOLDER') }}`.replace('PLACEHOLDER', fundId), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({code: newCode, name: newName})
                });
                const result = await response.json();

                if (result.success) {
                    // 前端动态更新表格行
                    const row = document.querySelector(`tr[data-fund-id="${fundId}"]`);
                    if (row) {
                        row.querySelector('.fund-code').textContent = newCode;
                        row.querySelector('.fund-name').textContent = newName;
                        row.classList.add('update-row'); // 添加更新动画
                        setTimeout(() => row.classList.remove('update-row'), 1500);
                    }
                    showMessage('基金更新成功', 'success');
                    closeModal('edit-fund-modal');
                } else {
                    showMessage(result.error, 'error');
                }
            } catch (error) {
                console.error('更新失败:', error);
                showMessage('更新失败', 'error');
            } finally {
                // 恢复按钮状态
                saveBtn.disabled = false;
                saveText.style.display = 'inline';
                saveLoading.style.display = 'none';
            }
        });

        // ------------ 删除基金功能 ------------
        function bindDeleteEvent(button) {
            button.addEventListener('click', async function() {
                const fundId = this.getAttribute('data-fund-id');
                const row = this.closest('tr');
                const fundCode = row.querySelector('.fund-code').textContent;

                if (!confirm(`确定要删除基金 ${fundCode} 吗？`)) {
                    return;
                }

                // 显示加载状态
                this.disabled = true;
                this.textContent = '删除中';

                try {
                    // 注意：使用新的API路径
                    const response = await fetch(`{{ url_for('fund_config.delete_fund', fund_id='PLACEHOLDER') }}`.replace('PLACEHOLDER', fundId), {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'}
                    });
                    const result = await response.json();

                    if (result.success) {
                        // 动画删除行
                        row.classList.add('delete-row');
                        setTimeout(() => row.remove(), 500);
                        showMessage('基金删除成功', 'success');
                    } else {
                        showMessage(`删除失败：${result.error}`, 'error');
                        this.disabled = false;
                        this.textContent = '删除';
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    showMessage('删除失败', 'error');
                    this.disabled = false;
                    this.textContent = '删除';
                }
            });
        }

        // 初始化所有按钮事件
        document.addEventListener('DOMContentLoaded', () => {
            // 绑定编辑按钮事件
            document.querySelectorAll('.edit-fund-btn').forEach(btn => {
                bindEditEvent(btn);
            });

            // 绑定删除按钮事件
            document.querySelectorAll('.delete-btn').forEach(btn => {
                bindDeleteEvent(btn);
            });
        });
    </script>
{% endblock %}